package com.plum.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class TestLengthFieldDecoder {
    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024,0,4,1,5),
                new LoggingHandler(LogLevel.DEBUG)
        );
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        send(buffer, "Hello word");
        send(buffer, "OK");
        channel.writeInbound(buffer);

    }
    private static void send(ByteBuf buf, String content){
        byte[] bytes = content.getBytes();
        int len = bytes.length;
        buf.writeInt(len);
        buf.writeByte(1);
        buf.writeBytes(bytes);
    }
}
//20:29:55.301 [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 10B
//        +-------------------------------------------------+
//        |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
//        +--------+-------------------------------------------------+----------------+
//        |00000000| 48 65 6c 6c 6f 20 77 6f 72 64                   |Hello word      |
//        +--------+-------------------------------------------------+----------------+
//        20:29:55.301 [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 2B
//        +-------------------------------------------------+
//        |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
//        +--------+-------------------------------------------------+----------------+
//        |00000000| 4f 4b                                           |OK              |
//        +--------+-------------------------------------------------+----------------+